import * as tools from 'src-ssr/util/common';
import { Sequelize, Op } from 'sequelize';
import models from 'src-ssr/db/sequelize';
/**
 * @function 记录操作日志
 * @param {object} user 用户信息{id, nickname}
 * @param {object} operate 操作内容{type, model, content}
 *                 type:操作类型 login/logout/open/add/edit/del
 *                 model:操作模块
 *                 content:操作内容
 * @param {object} device 客户端设置信息 {ip, browser, os}
 *                 ip:IP地址
 *                 browser:浏览器
 *                 os:操作系统
 */
const recordLogs = async (user, operate, device) => {
  const logs = {
    create_time: Date.now() / 1000
  };
  if (user) {
    logs.user_id = user.id;
    logs.user_name = user.nickname;
  }
  if (operate) {
    logs.oper_type = operate.type;
    logs.oper_model = operate.model || '';

    // 把所有的字符型对象全都parse后再stringify
    if (typeof operate.content === 'object') {
      tools.parseAllJSON(operate.content);
      logs.oper_content = JSON.stringify(operate.content, undefined, 2);
    } else {
      logs.oper_content = operate.content || '';
    }
  }
  // console.log(user, operate, device);
  if (device) {
    if (device.get) { // req类型的
      logs.ip = tools.getIP(device);
      logs.browser = device.get('browser') || '';
      logs.os = device.get('os') || '';
    } else { // 数据包类型的
      logs.ip = typeof device.ip === 'object' && device.ip ? device.ip[0] : device.ip;
      logs.browser = device.browser;
      logs.os = device.os;
    }
  }
  // console.log(logs);
  // const ret = await db.insertOne('operation_logs', logs);
  // 根据ip查询地理位置
  models.m_ip.findOne({
    attributes: ['local'],
    where: {
      [Op.and]: [
        Sequelize.where(Sequelize.fn('INET_ATON', logs.ip), Op.between, [
          Sequelize.fn('INET_ATON', Sequelize.col('start_ip')),
          Sequelize.fn('INET_ATON', Sequelize.col('end_ip'))
        ])
      ]
    }
  }).then(ret => {
    logs.geography = ret ? ret.local : '';
    // 保存日志
    models.t_operation_logs.create({ ...logs, tenant_id: user.tid });
  });
}

export default { recordLogs };
